home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 12516 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  57 lines

  1. Newsgroups: comp.lang.c++
  2. Path: news.athene.co.uk!not-for-mail
  3. From: "C.J. Scaife" <JOLTSWIFT@Athene.co.uk>
  4. Subject: Re: Help! Newbie question ...
  5. Message-ID: <314FDB55.3717@Athene.co.uk>
  6. Date: Wed, 20 Mar 1996 10:17:57 +0000
  7. References: <4ilkfu$41q@Kaos.deepcove.com>
  8. Organization: JoltSwift Ltd.
  9. X-Mailer: Mozilla 2.0GoldB1 (Win95; I)
  10. MIME-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13.  
  14. Sean Affleck wrote:
  15. > Is this legal ?
  16. > class A {...};
  17. > A f();
  18. > main() {
  19. >   A a = f();
  20. > }
  21. > A f()
  22. > {
  23. >    A fa;
  24. >    return fa;
  25. > }
  26. >         Can you create an object on the stack within a function and then return
  27. > the object ?  I know that objects created on the stack are deleted at block or
  28. >  function exit, so is it ok to return them and use the value to initialize
  29. > another object?
  30. >         I realize that there are ways to get around this such as dynamically
  31. > allocating the object and returning a pointer or passing the function an
  32. > object which the function can initialize in whatever way it wants.  However,
  33. > I'd like to know if this can be done 'cus it seems more tidy since the
  34. > returned object is automaticly deleted on block exit and can therefore be
  35. > ignored if not needed.  I'd also like to know for my own personal interest.
  36. >                                         Thanks!
  37. >         Sean Affleck
  38. >         nbennett@fraser.sfu.ca
  39.  
  40. It's legal, but inefficient because the local object will be copied to 
  41. the result space by the return statement. A better way is to construct 
  42. it in the return statement. An example of this can be found in my 
  43. which.cpp program documented at 
  44. http://www.athene.co.uk/Joltswift/csact003.htm (or get the source code 
  45. from CS_ACT.ZIP at that URL.
  46.  
  47. Hope this helps :)
  48.  
  49.